﻿using NLog;
using EpubFactory.Common;
using EpubFactory.Lib99.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace EpubFactory.Lib99
{
    static class Program
    {
        static readonly Logger _log = LogManager.GetLogger("Root");
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!AppProcessHelper.SetSingleInstance())
            {
                MessageBox.Show("程序已经在运行",
                                "发现多实例",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
                Environment.Exit(-1);
            }
            Application.ApplicationExit += Application_ApplicationExit;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Application.Run(new MainForm(new Lib99.Service.Lib99Receipe()));
        }

        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            AppProcessHelper.RestartIfRequired();
        }
        private static void ShowExceptionDetails(Exception Ex)
        {
            // Do logging of exception details

            // Let the user know that something serious happened...
            MessageBox.Show(Ex.Message,
                            Ex.TargetSite.ToString(),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);

            // better not try and restart as we might end up in an endless exception loop....
            AppProcessHelper.PreventRestart();

            // ask the app to shutdown...
            Application.Exit();
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _log.Error("线程异常", (Exception)e.ExceptionObject);
            ShowExceptionDetails((Exception)e.ExceptionObject);
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            _log.Error("线程异常", e.Exception);
            ShowExceptionDetails(e.Exception);
        }
    }
}
